import copy
import os

from src.log.logger import logger
from config.constants import DEP_PACKAGE_SPDX_ELEMENT_FORMAT, DEP_FILE_SPDX_ELEMENT_FORMAT
from config.common_enum_class import RelationshipType
from src.tools.query import RpmInfoQuery

class SbomRelationshipsElementGenerate:
    """
    generate sbom files element info for rpm
    """

    def __init__(self, relationship_element, rpm_path):
        """
        init relationship_element, rpm_path
        Args:
            relationship_element:
            rpm_path:
        Returns:
        """

        # self.package_element = package_element
        self.relationship_element = relationship_element
        self.rpm_path = rpm_path
        
    def generate_relationships_element(self, spdxelementId, rpm_depends: list, rpms_infos: dict, rpms_provides: dict):
        """
        merge new sbom  element jsons to sbom.json
        Args:
        Returns:
        """
        
        files_element = []
        recorded_deps = set()
        for dep in rpm_depends:
            if RpmInfoQuery.check_no_need_process_dep(dep) or dep in recorded_deps:
                continue
            recorded_deps.add(dep)
            # init depend_data for each dep
            depend_data = dict()
            depend_data = copy.copy(self.relationship_element)
            depend_data['spdxElementId'] = spdxelementId
            final_dep = dep
            # check dep: file/package
            if '/' in dep:
                final_dep = SbomRelationshipsElementGenerate.update_path_of_dep(dep)
                if final_dep in recorded_deps:
                    continue
                logger.info("get file dep: %s", final_dep)
                recorded_deps.add(final_dep)
                # check_sum = SbomPackagesElementGenerate.get_checksum()
                dep_check_sum = 'Unknown'
                depend_data['relatedSpdxElement'] = DEP_FILE_SPDX_ELEMENT_FORMAT.format(file_path=final_dep, check_sum=dep_check_sum)
            else:
                dep_rpm = rpms_provides.get(final_dep)
                dep_check_sum = ''
                if dep_rpm in recorded_deps:
                    continue
                recorded_deps.add(dep_rpm)
                if dep_rpm:
                    logger.info("get whatprovides from loacl: %s===%s", final_dep, dep_rpm)
                    dep_check_sum = rpms_infos.get(dep_rpm, {}).get('sha256sum', "")
                    dep_rpm = os.path.basename(dep_rpm).rsplit('-', 2)[0]
                else:
                    dep_rpm = RpmInfoQuery.query_dep_what_provides(final_dep, rpms_provides)
                    logger.info("get whatprovides from repo: %s===%s", final_dep, dep_rpm)
                    dep_check_sum = 'Unknown'
                    for key, value in rpms_infos.items():
                        if value.get("Name", "") == dep_rpm:
                            dep_check_sum = value.get('sha256sum', "")
                logger.info("get dep rpm for: %s====%s", final_dep, dep_rpm)
                depend_data['relatedSpdxElement'] = DEP_PACKAGE_SPDX_ELEMENT_FORMAT.format(rpm_name=dep_rpm, check_sum=dep_check_sum)
                
            depend_data['relationshipType'] = RelationshipType.DEPENDS_ON
            logger.info("get depend_data for:%s======[%s]", self.rpm_path, depend_data)
            files_element.append(depend_data)
            
        return files_element

    @staticmethod
    def update_path_of_dep(dep):
        """
        update valid path for dep
        Args:
            dep
        Returns:
        
        """
        
        final_dep = dep
        if 'bin' in dep or 'sbin' in dep:
            if 'usr' not in dep:
                final_dep = '/'.join(['/usr', dep])
        return final_dep